package com.demo.youxuanmall.controller;

import com.demo.youxuanmall.common.Result;
import com.demo.youxuanmall.entity.User;
import com.demo.youxuanmall.service.SystemSettingService;
import com.demo.youxuanmall.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Slf4j
@Controller
public class LoginController extends BaseController {

    private final UserService userService;

    public LoginController(SystemSettingService systemSettingService, UserService userService) {
        super(systemSettingService);
        this.userService = userService;
    }

    @GetMapping("/login")
    public String loginPage() {
        return "login";
    }

    @PostMapping("/api/login")
    @ResponseBody
    public Result<User> login(@RequestBody User loginUser, HttpSession session) {
        log.info("用户登录请求: username={}", loginUser.getUsername());
        log.info("当前Session ID: {}, 是否是新Session: {}", session.getId(), session.isNew());
        
        try {
            Result<User> result = userService.login(loginUser, session);
            if (result.getCode() == 0) {
                User user = result.getData();
                log.info("用户 {} 登录成功, 用户ID: {}, 角色: {}", loginUser.getUsername(), user.getId(), user.getRole());
                log.info("Session中的用户信息: {}", session.getAttribute("user"));
            } else {
                log.warn("用户 {} 登录失败: {}", loginUser.getUsername(), result.getMsg());
            }
            return result;
        } catch (Exception e) {
            log.error("用户 {} 登录发生异常", loginUser.getUsername(), e);
            return Result.error("登录处理异常: " + e.getMessage());
        }
    }

    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "redirect:/login";
    }
} 